package com.service.config.utils;

import com.github.pagehelper.PageInfo;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;

import java.util.ArrayList;
import java.util.List;

/**
 * 转换工具
 * @ClassName ModelMapperUtil
 * @Description TODO
 * @Author mmc
 * @Date 2019-10-24 09:00
 * @Version 1.0
 **/
public class ModelMapperUtil {

	private static ModelMapper modelMapper;

	static{
		modelMapper = new ModelMapper();
		//精准匹配
    	modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
	}

	/**
	 * dto转换-通用精确匹配
	 * (精确匹配是指只copy相同属性名的值)
	 * 自定义匹配规则请参考：http://modelmapper.org/getting-started/ 的‘Explicit Mapping’部分
	 * @param source
	 * @param destinationType
	 * @return
	 * @author Ivan
	 * @date 2016年6月21日 下午2:58:39
	 */
	public static <D> D strictMap(Object source,Class<D> destinationType){
		return modelMapper.map(source, destinationType);
	}

	/**
	 * List&lt;dto>转换
	 * @param source
	 * @param componentType
	 * @return
	 * @author Ivan
	 * @date 2016年6月21日 下午3:58:12
	 */
	@SuppressWarnings("unchecked")
	public static <D> List<D> strictMapList(Object source,final Class<D> componentType){
		List<D> list= new ArrayList<D>();
		List<Object> objectList = (List<Object>) source;
		for (Object obj : objectList) {
			list.add(modelMapper.map(obj, componentType));
		}
		return list;
	}

	/**
	 * Page&lt;dto>转换
	 * @param source
	 * @param componentType
	 * @return
	 * @author Ivan
	 * @date 2016年8月15日 下午3:58:12
	 */
	@SuppressWarnings("unchecked")
	public static <D> PageInfo<D> strictPageResult(Object source, final Class<D> componentType)
	{
		PageInfo<Object> objPage = (PageInfo<Object>) source;
		PageInfo<D> pageResult = new PageInfo<D>();
		pageResult.setTotal(objPage.getTotal());
		pageResult.setEndRow(objPage.getEndRow());
		pageResult.setFirstPage(objPage.getFirstPage());
		pageResult.setIsFirstPage(objPage.isIsFirstPage());
		pageResult.setLastPage(objPage.getLastPage());
		pageResult.setIsLastPage(objPage.isIsLastPage());
//		pageResult.setOrderBy(objPage.getOrderBy());
		pageResult.setNextPage(objPage.getNextPage());
		pageResult.setPageNum(objPage.getPageNum());
		pageResult.setNavigatepageNums(objPage.getNavigatepageNums());
		pageResult.setPages(objPage.getPages());
		pageResult.setSize(objPage.getSize());
		pageResult.setPrePage(objPage.getPrePage());
		pageResult.setPageSize(objPage.getPageSize());
		List<D> list= strictMapList(objPage.getList(), componentType);
		pageResult.setList(list);

		return pageResult;
	}

}
